﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;
using System.Configuration;
using SignalR.Hosting;
using System.Web;
using Microsoft.Owin.Hosting.Starter;

namespace Derrick.Web
{
    public partial class HttpStreamService : ServiceBase
    {
        private TraceSwitch _traceSwitch = new TraceSwitch("HTTP Stream Trace", "HTTP Stream Trace");
        private Broadcaster _broadcaster = null;
        private IDisposable _signalRService = null;
        private MessageHub _messageHub = null;

        public IDisposable SignalRService
        {
            get { return _signalRService; }
            set { _signalRService = value; }
        }

        public HttpStreamService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //string url = "http://localhost:1802";
            string url = ConfigurationManager.AppSettings["StreamingUrl"];
            System.Diagnostics.Trace.WriteLineIf(_traceSwitch.TraceVerbose, "The URL of the stream is: " + url);

            //using (WebApplication.Start<MessagePump>(url))
            //{
                //running.
                System.Diagnostics.Trace.WriteLineIf(_traceSwitch.TraceVerbose, "Starting an instance of the Broadcaster.");
                _broadcaster = new Broadcaster();
                //System.Diagnostics.Trace.WriteLineIf(_traceSwitch.TraceVerbose, "Starting an instance of the MessageHub.");
                //_messageHub = new MessageHub();
                System.Diagnostics.Trace.WriteLineIf(_traceSwitch.TraceVerbose, "Starting web application with MessagePump...");
                try
                {
                    //_signalRService = WebApplication.Start<MessagePump>(url);
                    //RouteTable.Routes.MapConnection<MyEndPoint>("echo", "/echo");
                    _signalRService = null;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLineIf(_traceSwitch.TraceVerbose, "Error thrown when starting the MessagePump: " + ex.ToString());
                }
                System.Diagnostics.Trace.WriteLineIf(_traceSwitch.TraceVerbose, "Started web application with MessagePump.");
            //}
        }

        protected override void OnStop()
        {
            System.Diagnostics.Trace.WriteLineIf(_traceSwitch.TraceVerbose, "Stopping the HTTP stream.");
            _broadcaster.Dispose();
        }

    }
}
